package com.licheedev.serialtool.comn;

import android.os.SystemClock;
import android.util.Log;

import com.licheedev.hwutils.ByteUtil;
import com.licheedev.myutils.LogPlus;
import com.licheedev.serialtool.comn.message.LogManager;
import com.licheedev.serialtool.comn.message.RecvMessage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 读串口线程
 */
public class SerialReadThread extends Thread {

    private static final String TAG = "SerialReadThread";

    public static long uartdataInLastTime = 0;    //有时候接收串口数据不会一次是传上来的,通常是两次
    public static String uartdataBufLast = "";    //保存上一次的数据

    private BufferedInputStream mInputStream;

    public SerialReadThread(InputStream is) {
        mInputStream = new BufferedInputStream(is);
    }

    @Override
    public void run() {
        byte[] received = new byte[1024];
        int size;

        LogPlus.e("开始读线程");

        while (true) {

            if (Thread.currentThread().isInterrupted()) {
                break;
            }
            try {

                int available = mInputStream.available();

                if (available > 0) {
                    size = mInputStream.read(received);
                    if (size > 0) {
                        onDataReceive(received, size);
                    }
                } else {
                    // 暂停一点时间，免得一直循环造成CPU占用率过高
                    SystemClock.sleep(1);
                }
            } catch (IOException e) {
                LogPlus.e("读取数据失败", e);
            }
            //Thread.yield();
        }

        LogPlus.e("结束读进程");
    }


    /**
     * 处理获取到的数据
     *
     * @param buffer
     * @param inSize
     */
    private void onDataReceive(byte[] buffer, int inSize) {
        int size = inSize;
        Log.i("serial", "串口1接收到数据，时间戳" + System.currentTimeMillis());
        if (System.currentTimeMillis() - uartdataInLastTime > 100) {
            //上次是完整的数据，并且距离上次的时间小于100ms，就把上一次的数据和这一次的数据合并
            uartdataBufLast = "";
        }
        size += uartdataBufLast.length();
        String s = uartdataBufLast + new String(buffer, 0, inSize);

        Log.i("serial", "接收串口数据1,数据长度" + inSize);
        String ss = "";
        for (int i = 0; i < inSize; i++) {
            ss += "0x" + Integer.toHexString(buffer[i]) + " ";
        }
        Log.i("serial", "数据->> " + ss);

        Log.i("serial", "完整数据->> " + s + "完整数据长度->>" + size);

        byte[] bufs = s.getBytes();

        if (bufs[bufs.length - 1] == 0x0A && bufs[bufs.length - 2] == 0x0D) {
            String handNo = s.replace("\n", "").replace("\r", "");
            LogManager.instance().post(new RecvMessage(handNo));
        } else {
            uartdataBufLast = s;
            //保存这次的接收的时间戳,方便判断分两次传上数据的情况
            uartdataInLastTime = System.currentTimeMillis();
            Log.d("serial", "长度不达标..时间戳->>" + uartdataInLastTime);
        }
    }

    /**
     * 停止读线程
     */
    public void close() {

        try {
            mInputStream.close();
        } catch (IOException e) {
            LogPlus.e("异常", e);
        } finally {
            super.interrupt();
        }
    }
}
